<template>
  <div 
    class="canvas-container"
    @dragover.prevent
    @dragenter.prevent
    @drop="handleDrop"
  >
    <canvas 
      id="designer-canvas" 
      ref="canvasRef"
      :style="{
        width: `${mmToPx(paperWidth)}px`,
        height: `${mmToPx(paperHeight)}px`
      }"
    ></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, defineExpose, watch } from 'vue';

const props = defineProps({
  paperWidth: {
    type: Number,
    default: 148
  },
  paperHeight: {
    type: Number,
    default: 105
  },
  pxPerMm: {
    type: Number,
    default: 3.78
  }
});

const emit = defineEmits(['drop', 'field-selected']);

const canvasRef = ref(null);

// 坐标转换函数 - 毫米转像素
const mmToPx = (mm) => {
  if (!mm && mm !== 0) return 0;
  return mm * props.pxPerMm;
};

// 监听pxPerMm和纸张尺寸变化
watch(() => props.pxPerMm, (newValue) => {
  console.log('CanvasPanel - pxPerMm变化为:', newValue);
}, { immediate: true });

watch([() => props.paperWidth, () => props.paperHeight], ([width, height]) => {
  console.log('CanvasPanel - 纸张尺寸变化为:', width, 'x', height);
}, { immediate: true });

// 处理拖放
const handleDrop = (event) => {
  event.preventDefault();
  
  // 获取拖放位置
  const rect = event.target.getBoundingClientRect();
  const left = event.clientX - rect.left;
  const top = event.clientY - rect.top;
  console.log('获取拖放event位置1:', event);
  console.log('获取拖放rect位置2:',rect);
  
  // 获取拖放数据
  const dropData = event.dataTransfer.getData('text/plain');
  if (!dropData) return;
  
  try {
    // 尝试解析拖放数据
    const fieldData = JSON.parse(dropData);
    
    // 添加拖拽位置信息
    fieldData.dropPosition = { left, top };
    if(fieldData.key.includes('verticalLine')){
      console.log('线条长度:', fieldData.Line[3]);
      fieldData.dropPosition.top =fieldData.dropPosition.top + (mmToPx(fieldData.Line[3])/2)
    }
    console.log('画布接收到拖拽数据:', fieldData.dropPosition);
    // 触发drop事件，传递字段数据和位置信息
    emit('field-selected', fieldData);
    emit('drop', fieldData);
    
    console.log(`拖拽字段(${fieldData.key})到位置: (${left}, ${top})`);
  } catch (error) {
    console.error('解析拖放数据失败:', error);
  }
};

onMounted(() => {
  console.log('CanvasPanel组件已挂载，canvas元素ID:', canvasRef.value?.id);
});

// 向父组件暴露mmToPx函数和canvasRef
defineExpose({
  mmToPx,
  canvasRef
});
</script>

<style lang="scss" scoped>
/* 在ruler.scss中已定义canvas样式 */
</style> 